package com.ruoyi.common.easyexcel;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.ruoyi.common.utils.DateUtils;
import org.apache.poi.ss.usermodel.DateUtil;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author :chenzengzhi
 * @date :2023/12/8 9:54
 * @logo :#^_^#
 */
public abstract class BaseConverter <T> implements Converter<T> {
    private Class<T> clazz;


    public BaseConverter(Class<T> clazz) {
        this.clazz = clazz;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public Class supportJavaTypeKey() {
        return clazz;
    }

    @Override
    public T convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,
                               GlobalConfiguration globalConfiguration) {

        // LocalDateTime 时间转换
        if (cellData.getData() instanceof LocalDate) {
            if (cellData.getType().equals(CellDataTypeEnum.NUMBER)) {
                LocalDate localDate = LocalDate.of(1900, 1, 1);
                localDate = localDate.plusDays(cellData.getNumberValue().longValue());
                return (T) localDate;
            } else if (cellData.getType().equals(CellDataTypeEnum.STRING)) {
                return (T) LocalDate.parse(cellData.getStringValue(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            } else {
                return null;
            }
        }

        // LocalDateTime 时间转换
        if (cellData.getData() instanceof LocalDateTime) {
            return (T) LocalDateTime.parse(cellData.getStringValue(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        }
        return null;

    }


    @Override
    public CellData convertToExcelData(T o, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        if (o instanceof LocalDate) {

            LocalDate localDate = DateUtils.parseLocalDate(o.toString(),"yyyy-MM-dd");
            return new CellData<>(localDate.toString());
        }

        if (o instanceof LocalDateTime) {
            LocalDateTime localDateTime = DateUtils.parse(o.toString().replace("T"," "),"yyyy-MM-dd HH:mm:ss");
        }

        return new CellData<>(o.toString());
    }
}
